# This file must be placed somewhere in one's PYTHONPATH. It is used to set
# up python paths to find meta source code. It relies on METAROOT being
# properly set.
import os
import sys

class Error(Exception):
  pass

Version = None
NewPythonPaths = []

def Metastrap(version=None, verbose=False):
  global Version
  if Version is None:
    metaroot = os.getenv('METAROOT')
    if metaroot is None:
      raise Error('METAROOT must be set to the root of the Meta directory.')
    if not version:
      version = os.getenv('META_VERSION', 'current')

    if verbose:
      print 'Loading %s version of metac' % version
    path1 = os.path.join(metaroot, 'lib', version, 'meta')
    path2 = os.path.join(metaroot, 'lib', version, 'python')
    for path in (path2, path1):
      RegisterPath(path, verbose=verbose)
    Version = version
  else:
    # We've already bootstrapped, and don't need to do so again.
    if version and version != Version:
      raise Error(
        'Metastrap called with version %s when env already strapped with %s' %
        (version, Version))
    pass


def RegisterPath(path, verbose=False):
  # Ensure that 'path' is in sys.path.
  if not os.path.exists(path):
    print 'ERROR: Failed to find %s' % path
    sys.exit(1)
  else:
    #print 'Adding %s to start of sys.path' % path
    sys.path.insert(0, path)
    NewPythonPaths.append(path)
    if verbose:
      print 'Adding %s to python path' % path

  # Ensure that 'path' is in PYTHONPATH
  env = os.environ
  pypath = env.get('PYTHONPATH', '')
  pylist = pypath.split(':')
  if path not in pylist:
    pypath = '%s:%s' % (path, pypath) if pypath else path
    env['PYTHONPATH'] = pypath
  
